package com.hotel.user.service;

import com.hotel.common.entity.User;
import com.hotel.common.entity.Role;
import com.hotel.common.utils.DBTools;
import com.hotel.common.utils.Result;
import com.hotel.user.mapper.UserMapper;
import com.hotel.user.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public Result<Long> register(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.findByUsername(user.getUsername());
        if (existingUser != null) {
            return Result.error("用户名已存在");
        }
        if (user.getPasswordBcrypt() == null || user.getPasswordBcrypt().isEmpty()) {
            return Result.error("密码不能为空");
        }

        // 密码加密
        String encodedPassword = passwordEncoder.encode(user.getPasswordBcrypt());
        user.setPasswordBcrypt(encodedPassword);
        
        // 设置默认状态
        user.setStatus(1); // 1表示正常状态
        
        Long userId = userMapper.insert(user);
        return Result.success(userId);
    }

    public Result<User> getUserById(Long id) {
        User user = userMapper.findById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    public Result<User> getUserByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    public Result<List<User>> getAllUsers() {
        List<User> users = userMapper.findAll();
        return Result.success(users);
    }

    public Result<Map<String, Object>> getAllUsersWithPagination(int page, int size) {
        // 分页查询用户
        String sql = "SELECT id, username, password_bcrypt, real_name, tel, status, created_at, updated_at FROM user ORDER BY created_at DESC LIMIT ? OFFSET ?";
        List<Map<String, String>> result = DBTools.query(sql, size, (page - 1) * size);
        List<User> users = result.stream().map(this::mapToUser).collect(Collectors.toList());
        
        // 查询总数
        String countSql = "SELECT COUNT(*) as total FROM user";
        List<Map<String, String>> countResult = DBTools.query(countSql);
        int total = Integer.parseInt(countResult.get(0).get("total"));
        
        Map<String, Object> response = new HashMap<>();
        response.put("data", users);
        response.put("total", total);
        response.put("page", page);
        response.put("size", size);
        
        return Result.success(response);
    }
    
    /**
     * 根据用户名搜索用户（分页）
     */
    public Result<Map<String, Object>> searchUsersByUsername(String username, int page, int size) {
        // 搜索用户
        String sql = "SELECT id, username, password_bcrypt, real_name, tel, status, created_at, updated_at FROM user WHERE username LIKE ? ORDER BY created_at DESC LIMIT ? OFFSET ?";
        String searchPattern = "%" + username + "%";
        List<Map<String, String>> result = DBTools.query(sql, searchPattern, size, (page - 1) * size);
        List<User> users = result.stream().map(this::mapToUser).collect(Collectors.toList());
        
        // 查询总数
        String countSql = "SELECT COUNT(*) as total FROM user WHERE username LIKE ?";
        List<Map<String, String>> countResult = DBTools.query(countSql, searchPattern);
        int total = Integer.parseInt(countResult.get(0).get("total"));
        
        Map<String, Object> response = new HashMap<>();
        response.put("data", users);
        response.put("total", total);
        response.put("page", page);
        response.put("size", size);
        
        return Result.success(response);
    }
    
    private User mapToUser(Map<String, String> map) {
        return User.builder()
                .id(Long.valueOf(map.get("id")))
                .username(map.get("username"))
                .passwordBcrypt(map.get("password_bcrypt"))
                .realName(map.get("real_name"))
                .tel(map.get("tel"))
                .status(Integer.valueOf(map.get("status")))
                .createdAt(LocalDateTime.parse(map.get("created_at").replace(" ", "T")))
                .updatedAt(LocalDateTime.parse(map.get("updated_at").replace(" ", "T")))
                .build();
    }

    public Result<List<User>> getUsersWithRoles() {
        // 查询所有用户及其角色
        String sql = "SELECT DISTINCT u.id, u.username, u.password_bcrypt, u.real_name, u.tel, u.status, u.created_at, u.updated_at " +
                    "FROM user u ORDER BY u.created_at DESC";
        List<Map<String, String>> result = DBTools.query(sql);
        List<User> users = result.stream().map(this::mapToUser).collect(Collectors.toList());
        
        // 为每个用户查询其角色信息
        for (User user : users) {
            List<Role> userRoles = getUserRoles(user.getId());
            user.setRoles(userRoles);
        }
        
        return Result.success(users);
    }
    
    /**
     * 获取用户的角色列表
     */
    private List<Role> getUserRoles(Long userId) {
        String sql = "SELECT r.id, r.role_name, r.role_code, r.description, r.created_at " +
                    "FROM role r " +
                    "INNER JOIN user_role ur ON r.id = ur.role_id " +
                    "WHERE ur.user_id = ?";
        List<Map<String, String>> result = DBTools.query(sql, userId);
        return result.stream().map(this::mapToRole).collect(Collectors.toList());
    }
    
    /**
     * 将数据库查询结果映射为Role对象
     */
    private Role mapToRole(Map<String, String> map) {
        return Role.builder()
                .id(Long.valueOf(map.get("id")))
                .roleName(map.get("role_name"))
                .roleCode(map.get("role_code"))
                .description(map.get("description"))
                .createdAt(LocalDateTime.parse(map.get("created_at").replace(" ", "T")))
                .build();
    }

    public Result<Long> createUser(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.findByUsername(user.getUsername());
        if (existingUser != null) {
            return Result.error("用户名已存在");
        }
        
        // 若传入明文密码在 passwordBcrypt 字段，则加密存储
        if (user.getPasswordBcrypt() != null && !user.getPasswordBcrypt().isEmpty()) {
            String encodedPassword = passwordEncoder.encode(user.getPasswordBcrypt());
            user.setPasswordBcrypt(encodedPassword);
        }

        Long userId = userMapper.insert(user);
        return Result.success(userId);
    }

    public Result<Void> updateUser(User user) {
        User existingUser = userMapper.findById(user.getId());
        if (existingUser == null) {
            return Result.error("用户不存在");
        }
        
        // 如果修改了用户名，检查新用户名是否已存在
        if (!existingUser.getUsername().equals(user.getUsername())) {
            User userWithSameName = userMapper.findByUsername(user.getUsername());
            if (userWithSameName != null) {
                return Result.error("用户名已存在");
            }
        }
        // 如果提供了新密码，进行加密
        if (user.getPasswordBcrypt() != null && !user.getPasswordBcrypt().isEmpty()
                && !user.getPasswordBcrypt().equals(existingUser.getPasswordBcrypt())) {
            String encodedPassword = passwordEncoder.encode(user.getPasswordBcrypt());
            user.setPasswordBcrypt(encodedPassword);
        }

        userMapper.update(user);
        return Result.success();
    }

    public Result<Void> deleteUser(Long id) {
        User user = userMapper.findById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 删除用户的角色关联
        userRoleMapper.deleteByUserId(id);
        // 删除用户
        userMapper.deleteById(id);
        return Result.success();
    }

    public Result<Void> assignRole(Long userId, Long roleId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        userRoleMapper.insert(userId, roleId);
        return Result.success();
    }

    public Result<Void> removeRole(Long userId, Long roleId) {
        userRoleMapper.deleteByUserIdAndRoleId(userId, roleId);
        return Result.success();
    }

    public Result<Void> assignRolesToUser(Long userId, List<Long> roleIds) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 先删除用户的所有角色
        userRoleMapper.deleteByUserId(userId);
        
        // 批量添加新角色
        if (roleIds != null && !roleIds.isEmpty()) {
            for (Long roleId : roleIds) {
                userRoleMapper.insert(userId, roleId);
            }
        }
        
        return Result.success();
    }
    
    /**
     * 带权限验证的角色分配方法
     * @param currentUserId 当前操作用户ID
     * @param targetUserId 目标用户ID
     * @param roleIds 要分配的角色ID列表
     * @return 操作结果
     */
    public Result<Void> assignRolesToUserWithPermission(Long currentUserId, Long targetUserId, List<Long> roleIds) {
        // 检查目标用户是否存在
        User targetUser = userMapper.findById(targetUserId);
        if (targetUser == null) {
            return Result.error("目标用户不存在");
        }
        
        // 超级管理员（ID=1）可以修改任何用户的角色
        if (currentUserId.equals(1L)) {
            return assignRolesToUser(targetUserId, roleIds);
        }
        
        // 检查当前用户是否有角色管理权限
        // 这里可以添加更详细的权限检查逻辑
        // 例如：检查当前用户是否有 "role:assign" 权限
        
        // 暂时允许所有已登录用户进行角色分配
        // 在实际应用中，应该根据具体的权限系统进行验证
        return assignRolesToUser(targetUserId, roleIds);
    }

    public Result<Void> removeAllRolesFromUser(Long userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        userRoleMapper.deleteByUserId(userId);
        return Result.success();
    }

    public Result<List<User>> getUsersByRoleId(Long roleId) {
        List<User> users = userMapper.findByRoleId(roleId);
        return Result.success(users);
    }
}